<?php

namespace app\api\controller;

use app\common\model\Config;
use think\facade\Db;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Media;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Article;
use app\common\model\User;

class Wechat{
    //支付密钥
    protected $appId;
    protected $key;
    protected $mch_id;
    protected $mpApp = null;
    protected $miniProgram = null;

    public function __construct(){
        //获取微信支付配置
        $wxConfig = Config::where("name","wxpay")->find();

        $this->appId = $wxConfig["config_value"]["appid"];
        $this->key = $wxConfig["config_value"]["key"];
        $this->mch_id = $wxConfig["config_value"]["mch_id"];

        //小程序配置
        $miniConfig = Db::name("system")->where("config","miniapp")->find();
        $config = [
            'app_id' => $miniConfig["value"],
            'secret' => $miniConfig["extend"],
            'response_type' => 'array',
        ];

        $this->miniProgram = Factory::miniProgram($config);
    }


    //小程序生成二维码
    public function makeQrCode($page,$scene,$name,$path){
        $response = $this->miniProgram->app_code->getUnlimit($scene, [
            'page'  => $page,
            'width' => 150,
        ]);

        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(root_path() .'public/qrcode/'.$path,$name);
            return [
                'success' => true,
                "src" => request()->domain().'/qrcode/' .$path .'/' .$filename
            ];
        }

        return [
            'success' => false,
            "msg" => $response
        ];
    }

    //小程序文本内容检测
    public function checkText($content){
        $result = $this->miniProgram->content_security->checkText($content);

        if($result["errcode"] === 0){
            return true;
        }

        return  false;
    }

    //小程序图片内容检测
    public function checkImage($url){
        $result = $this->miniProgram->content_security->checkImage($url);

        if($result["errcode"] === 0){
            return true;
        }

        return  false;
    }
}